package dotdashdot.bradz.trendsettr;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.Typeface;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;

//Dynamic Popup Window. This isn't as necessary anymore as the filters have been
//taken out until redesign.
public class ClassFilterPopup {
	private PopupWindow info_popup;
	private LinearLayout info_layout;
	//private Typeface font_italic,font_bold,font_book,font_title;
	private String info_text = "SORT TRENDS BY THE FOLLOWING CATEGORIES:";
	//private ArrayList<CheckBox> filters;
	private RadioGroup filters;
	//private ClassFonts fonts;
	private LinearLayout popup_layout_0;
	private LinearLayout popup_layout_1;
	private ScrollView scroll_layout_1;
	private boolean top_layout = false;
	private Context self;
	private ClassFonts fonts;
	private Handler myHandler;
	private boolean filter_opinions = false;
	private static LinearLayout.LayoutParams box_params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
	private ClassUberLogger logger;

	ClassFilterPopup(final Context self, ClassFonts fonts, ArrayList<String> topics, 
			final ListView list, final Context context, final ListView list_view, Handler myHandler, final boolean alt_adapter){
		logger = new ClassUberLogger("ClassFilterPopup");
		this.fonts = fonts;
		this.self = self;
		this.myHandler = myHandler;
		popup_layout_0 = new LinearLayout(self);
		popup_layout_0.setGravity(Gravity.LEFT);
        popup_layout_0.setPadding(5, 5, 5, 5);
    	CheckBox rated_subject = new CheckBox(self);
    	rated_subject.setText("See my trend ratings");
    	add_checkbox_formatting(rated_subject);
    	rated_subject.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    		   @Override
    		   public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
    			   logger.info("Filter by user choice clicked");
    			   filter_opinions = isChecked;
    			   list_view.invalidateViews();
    			   if(!alt_adapter){
        			   ClassTrendsettrAdapter adapter = (ClassTrendsettrAdapter) list_view.getAdapter();
        			   adapter.filter_opinions(isChecked);
    			   }else{
    				   ClassTrendsettrAdapterAlt adapter = (ClassTrendsettrAdapterAlt) list_view.getAdapter();
        			   adapter.filter_opinions(isChecked);
    			   }
    		   }
    	});
	    popup_layout_0.addView(rated_subject,box_params);
	    top_layout = true;
	    logger.info("Done creating top layers");
	    create_bottom_layers(self, fonts, topics);
	    add_layers();
	}
	
	
	ClassFilterPopup(final Context self, ClassFonts fonts, ArrayList<String> topics, Handler myHandler){
		this.fonts = fonts;
		this.self = self;
		this.myHandler = myHandler;
		create_bottom_layers(self, fonts, topics);
		add_layers();
	}
	
	public boolean get_filter_opinions(){
		return filter_opinions;
	}
	
	public void create_bottom_layers(final Context self, ClassFonts fonts, ArrayList<String> topics){
		//Filter stuff. Commented out until later...
		//font_italic = Typeface.createFromAsset(assets,"fonts/Neutraface2Text-BookItalic.otf");
        //font_bold = Typeface.createFromAsset(assets,"fonts/Neutraface2Text-Bold.otf");
		//font_book = Typeface.createFromAsset(assets,"fonts/Neutraface2Text-Book.otf");
		//font_title = Typeface.createFromAsset(assets,"fonts/Neutraface2Text-Demi.otf");
		
		/*
		 *  <CheckBox
         *   android:layout_marginTop="5dp"
	     *   android:id="@+id/check_box_real_time"
	     *   android:layout_width="wrap_content"
	     *   android:layout_height="wrap_content"
	     *   android:textColor="@color/text_color"
	     *   android:textSize="14sp"
	     *   android:button="@drawable/selector_check"
	     *   android:text="@string/network_settings_real_time" />
		 */
		
		//context.getResources().getColor(R.color.navigation_color)
	    //boolean first_set = false;
		
	    popup_layout_1 = new LinearLayout(self);
        popup_layout_1.setGravity(Gravity.LEFT);
        popup_layout_1.setPadding(5, 5, 0, 5);
	        TextView popUp_title = new TextView(self);
	        popUp_title.setTextSize(32);
	        popUp_title.setGravity(Gravity.LEFT);
	        popUp_title.setText(info_text);
	        popUp_title.setTextColor(self.getResources().getColor(R.color.popup_text));
	        popUp_title.setTypeface(fonts.get_font("cond_medium"));
        popup_layout_1.addView(popUp_title);
        
        scroll_layout_1 = new ScrollView(self);
        ScrollView.LayoutParams fieldparams = new ScrollView.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        scroll_layout_1.setPadding(5, 5, 5, 5);
        scroll_layout_1.setLayoutParams(fieldparams);
        	LinearLayout popup_layout_2 = new LinearLayout(self);
	        popup_layout_2.setGravity(Gravity.LEFT);
	        //Vertical
	        popup_layout_2.setOrientation(1);
	        //LinearLayout.LayoutParams checkboxLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
	        //checkboxLayoutParams.setMargins(0, 0, 0, 15);
        	//filters = new ArrayList<CheckBox>();
        	
        	filters = new RadioGroup(self);
        	
        	if(topics.size()<1){
        		topics.add("No More Topics");
        	}
        	for(String topic:topics){
        		RadioButton filter_item = new RadioButton(self);
        		Log.i("Filter_Topics",topic);
        		filter_item.setText(topic);
        		/*if(!first_set){
        			Log.i("Filter Item Set","Filter Item Set");
        			filter_item.setChecked(true);
        			first_set = !first_set;
        		}else{
        			filter_item.setChecked(false);
        		}*/
        		if(topic.equals("No More Topics")){
        			filter_item.setClickable(false);
        		}
        		
        		add_radio_button_formatting(filter_item);
        		
        		filter_item.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						logger.info("Sorting button clicked");
						if(myHandler!=null){
							myHandler.sendEmptyMessage(6);
						}
					}
		        });
        		
        		//filter_item.setBackgroundResource(R.drawable.button_square_edges_off);
        		/*filter_item.setOnCheckedChangeListener(new OnCheckedChangeListener() {
					@Override
					public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
						// TODO Auto-generated method stub
						if(myHandler!=null){
							myHandler.sendEmptyMessage(3);
						}
						
					}
		        });*/
        		filters.addView(filter_item,
        				new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
        		//filters.add(filter_item);
        	}
        	
        	//Set popularity as the default sort
        	((RadioButton) filters.getChildAt(0)).setChecked(true); 
	       //for (CheckBox filter:filters){
	       popup_layout_2.addView(filters,box_params);
	       //}
	    scroll_layout_1.addView(popup_layout_2,box_params); 
	    logger.info("Done creating bottom layers");
	}
	
	public void add_radio_button_formatting(RadioButton radioButton){
        float density = self.getResources().getDisplayMetrics().density;
        radioButton.setPadding(radioButton.getPaddingLeft() + (int)(20.0f * density + 0.5f),
        		radioButton.getPaddingTop() + (int)(10.0f * density + 0.5f),
        		radioButton.getPaddingRight(),
        		radioButton.getPaddingBottom() + (int)(10.0f * density + 0.5f));
        radioButton.setTextSize(24);
        radioButton.setTextColor(self.getResources().getColor(R.color.popup_text));
        radioButton.setButtonDrawable(R.drawable.selector_check);
        radioButton.setTypeface(fonts.get_font("medium"));
        radioButton.setBackgroundResource(R.drawable.checkbox_square_edges_off);
	}
	
	public void add_checkbox_formatting(CheckBox checkBox){
        float density = self.getResources().getDisplayMetrics().density;
		checkBox.setPadding(checkBox.getPaddingLeft() + (int)(20.0f * density + 0.5f),
		        checkBox.getPaddingTop() + (int)(10.0f * density + 0.5f),
		        checkBox.getPaddingRight(),
		        checkBox.getPaddingBottom() + (int)(10.0f * density + 0.5f));
		checkBox.setTextSize(24);
		checkBox.setTextColor(self.getResources().getColor(R.color.popup_text));
		checkBox.setButtonDrawable(R.drawable.selector_check);
		checkBox.setTypeface(fonts.get_font("medium"));
		checkBox.setBackgroundResource(R.drawable.checkbox_square_edges_off);
	}
	
	public void add_layers(){
		info_popup = new PopupWindow(self);
		
		info_layout = new LinearLayout(self);
		info_layout.setBackgroundColor(Color.WHITE);
		info_layout.setOrientation(1);
		info_layout.setGravity(Gravity.TOP);
		
	    //LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
	    box_params.setMargins(10, 10, 10, 40);
		if(top_layout){
	    	info_layout.addView(popup_layout_0,box_params);
	    }
		
		box_params.setMargins(10, 10, 10, 10);
	    info_layout.addView(popup_layout_1,box_params);
	    info_layout.addView(scroll_layout_1,box_params);

	    info_layout.setFocusable(true);
	    info_layout.setFocusableInTouchMode(true);
	    
	    info_popup.setContentView(info_layout);
	    info_popup.setFocusable(true);
	    
	    logger.info("Filter Popup Object Constructed");
	}
	
	public ArrayList<String> get_checked_filters(){

		ArrayList<String> return_list = new ArrayList<String>();
		for(int i = 0; i < filters.getChildCount(); i++){
			RadioButton btn = (RadioButton) filters.getChildAt(i);
			if(btn.getId() == filters.getCheckedRadioButtonId()){
				return_list.add(btn.getText().toString());
			}
		}
		logger.info("Finding filter items");
		for(String item:return_list){
			logger.info("Found: " + item);
		}
		return return_list;
	}
	
	public void attach_popup_window(View v, final Display display){
		v.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	Point size = new Point(display.getWidth(),display.getHeight());
            	info_popup.showAtLocation(info_layout, Gravity.CENTER, 0, 0);
            	info_popup.update(0, size.y/10, size.x, 9*size.y/10);
            }
        });
		logger.info("Popup attached to activity display");
	    myHandler.sendEmptyMessage(6);
	}
}
